package com.effectiv.gooruda.mvc.controller;

import javax.validation.Valid;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.effectiv.gooruda.business.api.EmailServerConfigurationService;
import com.effectiv.gooruda.domain.Application;
import com.effectiv.gooruda.domain.EmailServerConfiguration;
import com.effectiv.gooruda.mvc.argumentresolver.AjaxResponse;

@Slf4j
@Controller

public class EmailServerConfigurationController {
	@Autowired
	private EmailServerConfigurationService emailServerConfigurationService;
	
	@RequestMapping(value = "/newemailserver")
	public final String newApplication(Model model) {
			
		model.addAttribute(BeanUtils.instantiate(EmailServerConfiguration.class));
		return "newemailconfig";
	}
	
	@RequestMapping(value = "/saveemailconfig", method = RequestMethod.POST)
	public @ResponseBody
	AjaxResponse save(@Valid EmailServerConfiguration config, BindingResult result,
			AjaxResponse response) {
		
		log.debug("Configuring new email server - {}", config);
		
		if (!result.hasErrors()) {
			emailServerConfigurationService.save(config);
			response.setResult(config);
		} else {
			log.debug("Configuring new email server - {}", result);
			response.markValidationFailure(result.getFieldErrors());
		}
		log.debug("AjaxResponse = {}", response);
		return response;
	}
}
